// 项目运行时配置
// 具体配置可参考：https://umijs.org/zh-CN/docs/runtime-config
import React from 'react';
import {BasicLayoutProps, Settings as LayoutSettings} from '@ant-design/pro-layout';
import {notification, ConfigProvider} from 'antd';
import dayjs from 'dayjs';
import Cookie from 'js-cookie';
// import moment from 'moment';

import zhCN from 'antd/es/locale/zh_CN';
import 'dayjs/locale/zh-cn';
import RightContent from '@/components/RightContent';
import ErrorCom from '@/components/ErrorCom';
import defaultSettings from '../config/defaultSettings';
import {getAuth} from './services/user';

// 设置dayjs中文设置
dayjs.locale('zh-cn');
// moment.locale('zh-cn');

// @ts-ignore
if (CASTOKEN && NODE_ENV === 'development') {
    // @ts-ignore
    Cookie.set('_const_d_jsession_id_', CASTOKEN);
}

// 项目初始化全局状态
// 具体配置可参考：https://umijs.org/zh-CN/plugins/plugin-initial-state
export async function getInitialState(): Promise<{
    currentUser: API.CurrentUser | null;
    settings?: LayoutSettings;
    hasPermissions?: string[];
}> {
    try {
        const response = await getAuth();
        const hasPermissions
            = response?.data?.accountDto?.currentRole
                ?.hasPermissions?.map((item: API.PermissionItem) => item.tag) || [];
        return {
            currentUser: response?.data?.accountDto || null,
            hasPermissions,
            settings: defaultSettings,
        };
    }
    catch (error) {
        // window.location.href = `${window.location.origin}/main.do?referUrl=${location.href}`;
    }
    return {
        settings: defaultSettings,
        currentUser: null
    };
}

export function rootContainer(container: React.ReactNode) {
    return React.createElement(ConfigProvider, {locale: zhCN}, container);
}

// 项目布局配置
// 具体配置可参考：https://umijs.org/zh-CN/plugins/plugin-layout
export const layout = ({
    initialState,
}: {
    initialState: {settings?: LayoutSettings};
}): BasicLayoutProps => ({
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    footerRender: false,
    onError(error: any) {
        console.log('onError', error);
    },
    // @ts-ignore
    ErrorComponent(error) {
        console.log('进入', '/src/app.tsx:layout:ErrorComponent()', error);
        console.log('离开', '/src/app.tsx:layout:ErrorComponent()', error);
        return <ErrorCom error={error} />;
    },
    ...initialState?.settings,
});

// request全局配置
// 具体配置可参考：https://umijs.org/zh-CN/plugins/plugin-request
const codeMessage = {
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队（异步任务）。',
    204: '删除数据成功。',
    400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限（令牌、用户名、密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    405: '请求方法不被允许。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
};

/**
 * 异常处理程序
 */
const errorHandler = (error: {response: Response}) => {
    const {response} = error;
    if (response?.status) {
        // @ts-ignore
        const errorText = codeMessage[response.status] || response.statusText;
        const {status, url} = response;

        notification.error({
            message: `请求错误 ${status}: ${url}`,
            description: errorText,
        });
    }

    if (!response) {
        notification.error({
            description: '您的网络发生异常，无法连接服务器',
            message: '网络异常',
        });
    }
    throw error;
};

export const request = {
    errorHandler,
    errorConfig: {
        adaptor(resData) {
            return {
                ...resData,
                success: resData.code === 0,
                errorMessage: resData.msg,
            };
        },
    },
    responseInterceptors: [
        // @ts-ignore
        async function interceptors(res) {
            const resp = await (res || {}).clone().json();
            const {code, msg} = resp || {};
            if (code === 700) {
                window.location.href = `${window.location.origin}/main.do?referUrl=${location.href}`;
            }
            if (code !== 0) {
                notification.error({
                    message: msg || '网络请求失败, 请稍后重试'
                });
            }
            return res || {};
        },
    ]
};
